package com.example.controller;

import com.example.anno.TimeLog;
import com.example.pojo.Emp;
import com.example.pojo.Result;
import com.example.service.impl.EmpServiceImpl;
import com.example.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class LoginController {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private EmpServiceImpl empService;
    @PostMapping("/login")
    @TimeLog
    public Result login(@RequestBody Emp emp){
        log.info("接收到username,password:{},{}",emp.getUsername(),emp.getPassword());
        //此处返回查询到的员工的所有信息用于生成jwt令牌的负载部分,不能只用count统计查询到的员工数量来判断登录是否通过
        Emp empByNameAndPassword = empService.getEmpByNameAndPassword(emp);
        if(empByNameAndPassword==null) {
                log.info("未找到该用户信息");
                return Result.error("NOT_LOGIN");
        }
        else
        {
            log.info("用户信息检测成功,准备生成jwt令牌");
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", empByNameAndPassword.getUsername());
            claims.put("id", empByNameAndPassword.getId());
            claims.put("name", empByNameAndPassword.getName());
            String jwt = jwtUtils.generateJwtToken(claims);
            log.info("成功生成jwt令牌");
            return Result.succeed(jwt);
        }
    }
}
